package com.masterclient.app.businessmodule.homemodule.presenter;

import android.Manifest;
import android.content.Intent;
import android.os.Parcelable;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.eoner.baselibrary.base.BasePresenter;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.eoner.baselibrary.bean.firstpager.SignBean;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.UtilCollection;
import com.eoner.commonbean.banner.BannerNewItemBean;
import com.eoner.baselib.container.CommonBaseResponse;
import com.eoner.commonbean.popup.CommonPopUpBean;
import com.eoner.commonbean.product.ProductMessage;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.R;
import com.masterclient.app.base.CaptureActivity;
import com.masterclient.app.base.MessageCallBack;
import com.masterclient.app.businessmodule.homemodule.api.HomeRetrofitManager;
import com.masterclient.app.businessmodule.homemodule.bean.HomeIndexBean;
import com.masterclient.app.businessmodule.homemodule.bean.banner.BannerNewBean;
import com.masterclient.app.businessmodule.homemodule.bean.banner.SpecialImagBean;
import com.masterclient.app.businessmodule.homemodule.bean.footertab.HomeFooterTabData;
import com.masterclient.app.businessmodule.homemodule.bean.homecms.HomeCmsIndexBean;
import com.masterclient.app.businessmodule.homemodule.bean.homecms.HomeNewCmsIndexBean;
import com.masterclient.app.businessmodule.homemodule.bean.hot.HotSearchWordBean;
import com.masterclient.app.businessmodule.homemodule.bean.saletabs.FlashSaleTabBean;
import com.masterclient.app.businessmodule.homemodule.bean.saletabs.FlashSaleTabIndexBean;
import com.masterclient.app.businessmodule.homemodule.bean.search.SearchBoxBean;
import com.masterclient.app.businessmodule.homemodule.bean.shoplist.HomeShopListBean;
import com.masterclient.app.businessmodule.homemodule.bean.sign.HomeSignBean;
import com.masterclient.app.businessmodule.homemodule.fragment.HomePageNewFragment;
import com.masterclient.app.businessmodule.homemodule.presenter.data.HomeApiDataManager;
import com.masterclient.app.businessmodule.homemodule.presenter.sign.HomeSignManager;
import com.masterclient.app.businessmodule.homemodule.presenter.timetask.HomeTimerTask;
import com.masterclient.app.businessmodule.homemodule.presenter.timetask.IHomeTimerTask;
import com.masterclient.app.businessmodule.homemodule.view.IHomeMainView;
import com.masterclient.app.httpservice.RetrofitUtil;
import com.masterclient.app.httpservice.RetrofitUtil2;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.businessmodule.settingmodule.bankcard.bean.OperateResultBean;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.modules.goods.newpage.activity.NewCommodityDetailActivity;
import com.masterclient.app.modules.search.SearchHistoryActivity;
import com.masterclient.app.utils.CommonUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

public class HomePresenter extends BasePresenter implements IHomePresenter {

    private static final int REQUEST_CODE = 111;
    private static final String PAGE_SIZE = "20";
    private int page = 1;

    //TODO:interface
    private HomePageNewFragment iHomePageNewFragment;
    private IHomeMainView iHomeMainView;
    private IHomeTimerTask iHomeTimerTask;

    //TODO:manager
    //权限管理
    private RxPermissions rxPermissions;
    //签到管理
    private HomeSignManager mHomeSignManager;
    //缓存管理
    private HomeApiDataManager mHomeApiDataManager;

    //TODO:disposable
    private Disposable scaleDisposable;
    private Disposable homeDisposable;


    private HomeSignManager getHomeSignManager() {
        if (mHomeSignManager == null) {
            mHomeSignManager = new HomeSignManager();
        }
        return mHomeSignManager;
    }

    private HomeApiDataManager getHomeApiDataManager() {
        if (mHomeApiDataManager == null) {
            mHomeApiDataManager = new HomeApiDataManager();
        }
        return mHomeApiDataManager;
    }

    @Override
    public void onStart() {

    }

    /**
    * 绑定
    * */
    @Override
    public HomePresenter bindViewAndInteraction(IHomeMainView iHomeMainView, HomePageNewFragment iHomePageNewFragment) {
        this.rxPermissions = new RxPermissions(iHomePageNewFragment.getActivity());
        this.mHomeSignManager = new HomeSignManager();
        this.iHomeTimerTask = new HomeTimerTask().bindViewAndInteraction(iHomeMainView,iHomePageNewFragment);
        this.iHomePageNewFragment = iHomePageNewFragment;
        this.iHomeMainView = iHomeMainView;
        return this;
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                   接口
    //
    /////////////////////////////////////////////////////////////////////////////////


    @Override
    public int getCurrentPage() {
        return page;
    }

    /**
     * 首页接口
     * */
    @Override
    public void serviceApiHomeData() {
        page = 1;
        if (scaleDisposable != null && !scaleDisposable.isDisposed()) {
            scaleDisposable.dispose();
        }
        if (homeDisposable != null && !homeDisposable.isDisposed()) {
            homeDisposable.dispose();
        }
        Observable<HomeIndexBean> observable = HomeRetrofitManager.getInstance().getHomeData();
        Disposable disposable = toSubscribe(observable, (Consumer<HomeIndexBean>) bean -> {
            if (bean!=null && bean.getData()!=null) {
                if (iHomeMainView != null) {
                    getHomeApiDataManager().setFirstLoad(true);
                    //清空上次的缓存
                    getHomeApiDataManager().clearCache();
                    //开始刷新页面
                    iHomeMainView.finishRefresh(true);
                    //0.重置首页状态
                    iHomeMainView.refreshHomeDataToResetListState();
                    //1.处理搜索栏
                    progressSearchData(bean.getData().getSearch_box());
                    //2.处理消息红点
                    progressMessageRed(bean.getData().getNotice_num());
                    //3.处理热搜词和banner
                    progressBannerAndHotSearch(bean.getData().getHot_search_words(), bean.getData().getBanner());
                    //4.处理签到信息
                    progressSignData(bean.getData().getSign_guide());
                    //5.处理正品广告
                    progressFeatureData(bean.getData().getFeature());
                    //6.处理金刚区
                    progressDiamondsData(bean.getData().getDiamonds());
                    //6.1.固定两张占位图片
                    progressTwoPicData(bean.getData().getSpecialImag());
                    //7.处理胶囊区
//                    progressCapsulesData(bean.getData().getCapsules());
                    //8.处理大促区
                    progressPromotionsData(bean.getData().getNewPromotions());
                    //9.处理新三张图一排
//                    progressFirstPorcelainsData(bean.getData().getFirst_porcelains());
                    //10.处理直播模块1
//                    progressSecondLiveData(bean.getData().getSecond_porcelains());
                    //11.处理网格布局
//                    progressThreePorcelainsData(bean.getData().getThird_porcelains());
                    //12.处理直播模块2
//                    progressFourthLiveData(bean.getData().getFourth_porcelains());
                    //13.处理限时购
//                    List<FlashSaleTabBean>saleTabBeans = bean.getData().getFlash_sale_tabs();
//                    progressSaleData(saleTabBeans,bean.getData().getFirstSelSaleIndex(),bean.getData().getFlash_sale_products());
                    //14.处理为你精选
                    progressTemplate(bean.getData().getBrand_list_url(),bean.getData().getBrand_recommend());
                    //15.处理专题精选
//                    progressSpecial(bean.getData().getSpecial_cms());
                    //16.处理底部tab
                    progressFooterTiltle();
//                    progressFooterTab(bean.getData().getFooter_product_tabs_obj(), bean.getData().getFooter_tab_switch());
                    //加载完成
                    iHomeMainView.refreshHomeDataToEnd();
                }
            } else {
                if (iHomeMainView != null) {
                    iHomeMainView.finishRefresh(false);
                }
                if (iHomePageNewFragment != null && iHomePageNewFragment.isVisible()) {
                    iHomePageNewFragment.showToast(bean.getMsg());
                }
            }
        },  new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                if (iHomeMainView != null) {
                    iHomeMainView.finishRefresh(false);
                }
                if (!getHomeApiDataManager().isFirstLoad()) {
                    iHomeMainView.showErrorView();
                }
                if (iHomePageNewFragment != null && iHomePageNewFragment.isVisible()) {
                    iHomePageNewFragment.showToast("请检查网络连接");
                }
            }
        });

    }

    @Override
    public void serviceApiHomeDataOnlyToSale() {
        if (scaleDisposable != null && !scaleDisposable.isDisposed()) {
            scaleDisposable.dispose();
        }
        Observable<HomeIndexBean> observable = HomeRetrofitManager.getInstance().getHomeData();
        Disposable disposable = toSubscribe(observable, (Consumer<HomeIndexBean>) bean -> {
            if (bean!=null && bean.getData()!=null) {
                if (iHomeMainView != null) {
                    List<FlashSaleTabBean>saleTabBeans = bean.getData().getFlash_sale_tabs();
                    progressOnlySaleData(saleTabBeans,bean.getData().getFirstSelSaleIndex(),bean.getData().getFlash_sale_products());
                }
            }
        },  new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
            }
        });
        homeDisposable = disposable;

    }

    /**
     * 处理搜索栏
     * */
    private void progressSearchData(SearchBoxBean searchBoxBean) {

        if (iHomeTimerTask != null) {
            iHomeTimerTask.stopSearchTimerTask();
        }
        //TODO:缓存搜索词
        getHomeApiDataManager().setSearchWords(searchBoxBean.getSearch_words());
        //保存全局临时变量
        if (searchBoxBean.getSearch_words() != null && searchBoxBean.getSearch_words().size() > 0) {
            Config.search_term_keyword = searchBoxBean.getSearch_words();
            //开始计时任务
            if (iHomeTimerTask != null) {
                iHomeTimerTask.executeHomeSearchTimerTask(searchBoxBean.getSearch_words(),Integer.parseInt(searchBoxBean.getCycle_time()));
            }
        } else {
            Config.search_term_keyword = null;
        }
    }

    /**
     * 消息红点
     * */
    private void progressMessageRed(String noticeNum) {
        if (iHomeMainView != null) {
            if (Integer.parseInt(noticeNum) >= 1) {
                iHomeMainView.refreshHomeDataToRedImageState(false,noticeNum);
            } else {
                iHomeMainView.refreshHomeDataToRedImageState(true,noticeNum);
            }
        }
    }

    /**
     * banner和热搜词
     * */
    private void progressBannerAndHotSearch(List<HotSearchWordBean>hotSearchWordBeanList, BannerNewBean bannerBean) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToBannerAndHot(hotSearchWordBeanList,bannerBean);
        }
    }

    /**
     * 签到
     * */
    private void progressSignData(HomeSignBean signBean) {
        getHomeSignManager().updateMySignData(signBean);
        if (iHomeMainView != null) {
            if (signBean.isIs_signed()) {
                iHomeMainView.refreshSignData(signBean.getSigned_icon());
            } else {
                iHomeMainView.refreshSignData(signBean.getUnsigned_icon());
            }
        }
    }

    /**
    * 正品广告
    * */
    private void progressFeatureData(BannerNewBean featureBean) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToFeature(featureBean);
        }
    }

    /**
    * 固定两张占位图片
    * */
    private void progressTwoPicData(SpecialImagBean featureBean) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToTwoPic(featureBean);
        }
    }

    /**
    * 金刚区
    * */
    private void progressDiamondsData(BannerNewBean diamondsData) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToDiamonds(diamondsData);
        }
    }

    /**
     * 胶囊区
     * */
    private void progressCapsulesData(List<BannerNewItemBean>capsulesData) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToCapsules(capsulesData);
        }
    }

    /**
     * 大促区
     * */
    private void progressPromotionsData(BannerNewBean promotionsData) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToPromotionsAndGradual(promotionsData);
        }
    }

    /**
     * 新三张图一排
     * */
    private void progressFirstPorcelainsData(List<BannerNewItemBean>firstPorcelainData) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToFirstPorcelains(firstPorcelainData);
        }
    }

    /**
     * 直播模块1
     * */
    private void progressSecondLiveData(List<BannerNewItemBean>secondLiveData) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToSecondLive(secondLiveData);
        }
    }

    /**
     * 网格布局
     * */
    private void progressThreePorcelainsData(List<BannerNewItemBean>threePorcelainData) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToThreePorcelains(threePorcelainData);
        }
    }

    /**
     * 直播模块2
     * */
    private void progressFourthLiveData(List<BannerNewItemBean>fourthPorcelainData) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToFourthLive(fourthPorcelainData);
        }
    }

    /**
    * 限时购
    * */
    private void progressSaleData(List<FlashSaleTabBean>tabBeanList,int firstSelIndex, List<ProductMessage>firstShops) {
        //TODO:缓存限时购信息
        getHomeApiDataManager().setFlashSaleTabs(tabBeanList);
        if (iHomeMainView != null) {
            if (tabBeanList.size() > 0) {
                FlashSaleTabBean flashSaleTabBean = tabBeanList.get(firstSelIndex);
                flashSaleTabBean.setExtShopList(firstShops);
            }
            iHomeMainView.refreshHomeDataToFirstSale(tabBeanList);
        }
    }

    /**
     * 仅处理限时购
     * */
    private void progressOnlySaleData(List<FlashSaleTabBean>tabBeanList,int firstSelIndex, List<ProductMessage>firstShops) {
        //TODO:缓存限时购信息
        getHomeApiDataManager().setFlashSaleTabs(tabBeanList);
        if (iHomeMainView != null) {
            if (tabBeanList.size() > 0) {
                FlashSaleTabBean flashSaleTabBean = tabBeanList.get(firstSelIndex);
                flashSaleTabBean.setExtShopList(firstShops);
            }
            iHomeMainView.refreshHomeDataToAllSelSale(tabBeanList);
        }
    }

    /**
    * 为你精选
    * */
    private void progressTemplate(String brand_list_url,List<HomeNewCmsIndexBean> homeCmsIndexBean) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToTemplateCms(brand_list_url,homeCmsIndexBean);
        }
    }

    /**
     * 专题精选
     * */
    private void progressSpecial(HomeCmsIndexBean specialCmsIndexBean) {
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToSpecialCms(specialCmsIndexBean);
        }
    }

    /**
     * 处理底部title
     * */
    private void progressFooterTiltle() {
        if (iHomeMainView != null) {
            iHomeMainView.refreshFooterTiltle();
        }
    }

    /**
    * 处理底部tab
    * */
    private void progressFooterTab(HomeFooterTabData tabBeanList, String footerTabSwitch) {
        //TODO:保存底部tab
        getHomeApiDataManager().setTabBeanList(tabBeanList.getList());
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToFooterTab(tabBeanList,footerTabSwitch);
            if (tabBeanList.getList().size() > 0) {
//                iHomeMainView.refreshHomeFirstLoadFooterShopList(tabBeanList.getList());
            } else {
//                iHomeMainView.noMoreData();
            }
        }
    }

    @Override
    public void serviceApiSign() {
        if (iHomePageNewFragment == null) return;
        if (!UserDataManager.getInstance().isSystemLogin()) {
            iHomePageNewFragment.startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "首页"}});
        } else {
            //TODO:拿到缓存的数据 (暂时这样处理)
            HomeSignBean signBean = getHomeSignManager().getSignData();
            if (signBean != null && !TextUtils.isEmpty(signBean.getTask_url())) {
                if (!signBean.isIs_signed()) {
                    RetrofitUtil.getInstance().signInfo().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<CommonBaseResponse<SignBean>>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(CommonBaseResponse<SignBean> bean) {
                                    if (bean.getCode() == 0){
                                        //TODO:统一走通知
                                        eventBusToRefreshSignState();
                                        Intent intent = new Intent(iHomePageNewFragment.getActivity(), BridgeActivity.class);
                                        intent.putExtra("url", signBean.getTask_url());
                                        intent.putExtra("sign_day", bean.getData().getSh_sign_day_num());
                                        intent.putExtra("sign_bupiao",bean.getData().getSh_bupiao());
                                        intent.putExtra("sign_integral", bean.getData().getSh_integral());
                                        intent.putExtra("sign_coupon", bean.getData().getSh_coupon());
                                        intent.putParcelableArrayListExtra("sign_list", (ArrayList<? extends Parcelable>)bean.getData().getSh_recommend_product());
                                        iHomePageNewFragment.startActivity(intent);
                                    } else {
                                        if (bean.getCode() == 80003) {
                                            eventBusToRefreshSignState();
                                            iHomePageNewFragment.startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", signBean.getTask_url()}});
                                        } else {
                                            ToastUtil.showToast(bean.getMsg());
                                        }

                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    e.printStackTrace();
                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                } else {
                    iHomePageNewFragment.startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", signBean.getTask_url()}});
                }
            }
        }
    }

    @Override
    public void serviceSetRemindSale(String event_map_id,String product_id,String remindState,int selChildPosition) {
        RetrofitUtil.getInstance().setSaleRemain(event_map_id,product_id,remindState).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<OperateResultBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OperateResultBean operateResultBean) {
                if("0".equals(operateResultBean.getCode())){
                    //TODO:刷新限时购
                    serviceSaleDatas(event_map_id,selChildPosition);
                    if ("1".equals(remindState)) {
                        ToastUtil.showToast("预约成功，系统会在活动开始前5分钟通知您");
                    }
                } else {
                    ToastUtil.showToast(operateResultBean.getMsg());
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast(e.toString());
            }
            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void serviceSaleDatas(String event_map_id,int selChildPosition) {
        if (scaleDisposable != null && !scaleDisposable.isDisposed()) {
            scaleDisposable.dispose();
        }
        Observable<FlashSaleTabIndexBean> observable = HomeRetrofitManager.getInstance().getFlashSaleList(event_map_id);
        scaleDisposable = toSubscribe(observable, (Consumer<FlashSaleTabIndexBean>) bean -> {
            if (bean!=null && bean.getData()!=null && iHomeMainView != null) {
                if (getHomeApiDataManager().getFlashSaleTabs()!=null) {
                    //TODO:刷新限时购
                    List<FlashSaleTabBean>flashSaleTabBeanList = getHomeApiDataManager().getFlashSaleTabs();
                    if (flashSaleTabBeanList != null && flashSaleTabBeanList.size() > 0) {
                        //限时购商品列别赋值
                        FlashSaleTabBean flashSaleTabBean = flashSaleTabBeanList.get(selChildPosition);
                        flashSaleTabBean.setExtShopList(bean.getData().getFlash_sale_products());
                        //刷新view
                        iHomeMainView.refreshHomeDataToSelSale(flashSaleTabBeanList,selChildPosition,flashSaleTabBean.getStatus());
                    }
                }
            }
        },  new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                if (iHomePageNewFragment != null && iHomePageNewFragment.isVisible()) {
                    iHomePageNewFragment.showToast("请检查网络连接");
                }
            }
        });
    }

    @Override
    public void serviceFooterNewShopDataLoadMore(int index,boolean loadMore) {
        //TODO:先兼容
        if (index == -1) {
            index = getHomeApiDataManager().getFooterTabIndex();
        }
        getHomeApiDataManager().setFooterTabIndex(index);

        Observable<HomeShopListBean> observable = HomeRetrofitManager.getInstance().getHomeFooterShopList("",String.valueOf(page),PAGE_SIZE);
        int finalIndex = index;
        toSubscribe(observable, (Consumer<HomeShopListBean>) bean -> {
            if (bean!=null && bean.getData()!=null && iHomeMainView != null) {
                if (bean.getData().isHas_more()) {
                    iHomeMainView.finishLoadMore();
                } else {
                    iHomeMainView.noMoreData();
                }
                //刷新页面
                iHomeMainView.loadMoreHomeDataToFooterShopList(finalIndex,bean.getData().getProducts());
                //page++
                page++;
            }
        },  new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                if (iHomePageNewFragment != null && iHomePageNewFragment.isVisible()) {
                    iHomePageNewFragment.showToast("请检查网络连接");
                }
            }
        });

    }

    @Override
    public void serviceGetPopUpData(String page_type, MessageCallBack<List<CommonPopUpBean>> callBack) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("scene",page_type);
            jsonObject.put("scene_value",new JSONObject());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());

        RetrofitUtil2.getInstance().commonDialogData(body).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommonBaseResponse<List<CommonPopUpBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CommonBaseResponse<List<CommonPopUpBean>> bean) {
                        if (bean.getCode() == 0){
                            callBack.onSuccess(bean.getData());
                        }else {
                            callBack.onFail();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        callBack.onError(e.toString());
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                    事件
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    public void interactionToOpenQrPage() {

        if (iHomePageNewFragment == null) return;
        if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
            iHomePageNewFragment.startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "扫一扫"}});
        } else {
            boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.CAMERA);
            if (!hasPermissions){
                new PermissionDialog(iHomePageNewFragment.getActivity(), "开启摄像头权限","获取摄像头和相册权限以便扫码，请在下一个页面点击“允许”",
                        R.mipmap.icon_permission_phone,this::requestPermissions).show();
            }else {
                Intent intent = new Intent(iHomePageNewFragment.getContext(), CaptureActivity.class);
                try {
                    iHomePageNewFragment.getActivity().startActivityForResult(intent, REQUEST_CODE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void requestPermissions(){
        rxPermissions
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                        Intent intent = new Intent(iHomePageNewFragment.getContext(), CaptureActivity.class);
                        try {
                            iHomePageNewFragment.getActivity().startActivityForResult(intent, REQUEST_CODE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                    }
                });
    }

    @Override
    public void interactionToOpenMessagePage() {
        //TODO:点击红点消失
        if (iHomeMainView != null) {
            iHomeMainView.refreshHomeDataToRedImageState(true,"");
        }
        if (iHomePageNewFragment != null) {
            if (!UserDataManager.getInstance().isSystemLogin()) {
                iHomePageNewFragment.startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "首页"}});
            } else {
                CommonUtil.goAnyWhere(iHomePageNewFragment.getActivity(), SystemConfigStorage.getInstance().getMessageCenterUrl(), "", "", "", "");
            }
        }
    }

    @Override
    public void interactionSearchPage() {
        if (iHomePageNewFragment != null && iHomeMainView != null) {
            Intent intent = new Intent(iHomePageNewFragment.getContext(), SearchHistoryActivity.class);
            if (getHomeApiDataManager().getSearchWords() != null
                    && getHomeApiDataManager().getSearchWords().size() > 0) {
                intent.putExtra("hint_word", iHomeMainView.currentSearchTextView().getText().toString().trim());
            }
            iHomePageNewFragment.startActivity(intent);
        }
    }

    @Override
    public void interactionSale(String remindState, String productId, String mapId, int childPosition, String startTime) {
        if (iHomePageNewFragment != null) {
            switch (remindState) {
                case "0":
                    //其他
                    iHomePageNewFragment.startActivitryWithBundle(NewCommodityDetailActivity.class, new String[][]{{"id", productId}
                            , {"source_page", "首页"}, {"source_module", "限时购"}, {"source_element", startTime}, {"source_position", childPosition + ""}});
                    break;
                case "1":
                    //1: 未开抢（开抢提醒)
                    if (UserDataManager.getInstance().isSystemLogin()) {
                        //是否开启通知
                        if (!UtilCollection.isNotificationEnabled(iHomePageNewFragment.getActivity())) {
                            iHomePageNewFragment.displayNotificationTipDialog();
                        } else {
                            serviceSetRemindSale(mapId, productId, remindState, childPosition);
                        }
                    } else {
                        iHomePageNewFragment.startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "首页"}});
                    }
                    break;
                case "2":
                    //2: 取消提醒
                    if (UserDataManager.getInstance().isSystemLogin()) {
                        if (!UtilCollection.isNotificationEnabled(iHomePageNewFragment.getActivity())) {
                            iHomePageNewFragment.displayNotificationTipDialog();
                        } else {
                            serviceSetRemindSale(mapId, productId, remindState, childPosition);
                        }
                    } else {
                        iHomePageNewFragment.startActivitryWithBundle(QuickLoginActivity.class, new String[][]{{"intentSource", "首页"}});
                    }
                    break;
            }
        }
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                    通知事件部分处理
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    public void eventBusToSearchWord(String searchWord) {

        if (getHomeApiDataManager().getSearchWords() != null && getHomeApiDataManager().getSearchWords().size() > 0) {
             //...暂不处理
        } else {
            if (iHomeMainView != null) {
                iHomeMainView.currentSearchTextView().setText(searchWord);
            }
        }
        SPUtils.getInstance().put(Config.SEARCH_HINT, searchWord);
    }

    @Override
    public void eventBusToRefreshSignState() {
        HomeSignBean signBean = getHomeSignManager().getSignData();
        if (signBean != null && !TextUtils.isEmpty(signBean.getTask_url())) {
            signBean.setIs_signed(true);
            if (iHomeMainView != null) {
                if (signBean.isIs_signed()) {
                    iHomeMainView.refreshSignData(signBean.getSigned_icon());
                } else {
                    iHomeMainView.refreshSignData(signBean.getUnsigned_icon());
                }
            }
            getHomeSignManager().updateMySignData(signBean);
        }

    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                    定时任务
    //
    /////////////////////////////////////////////////////////////////////////////////
    @Override
    public void stopAllTimerTask() {
        mHomeSignManager = null;
        mHomeApiDataManager = null;
        if (iHomeTimerTask != null) {
            iHomeTimerTask.stopSearchTimerTask();
            iHomeTimerTask.stopXShopTimerTask();
        }
    }
}
